package chat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

public class ChatService {
	
	public ChatService(int port) throws IOException
	{
		StartChat(port);
	}
	
	public void StartChat(int port) throws IOException
	{	
		// repeatedly wait for connections, and process
        while (true) {
        	ServerSocket serverSocket = new ServerSocket(port);
            System.err.println("Connection Port:" + port);
            Socket clientSocket = serverSocket.accept();
            System.err.println("New Connection");

            BufferedReader in = new BufferedReader(
                           new InputStreamReader(clientSocket.getInputStream())
                          );
            //PrintWriter pr = new PrintWriter(clientSocket.getOutputStream());
            //DataOutputStream wr = new DataOutputStream(clientSocket.getOutputStream());
            

            String s;// = in.readLine();
            String msg = "test";
            int i = 0;
            //in.skip(303);
            
            
            //System.out.println(in.toString());
            while ((s = in.readLine()) != null) {
            //while ((s = in.readLine()).isEmpty()){
            	i++; 
                System.out.println(s);
                System.out.println(i);
                //get msg
            }
            
            //int i=0;
            //char[] buf = new char[10000];
            //while((i=in.read(buf,i,100))!= -1)
            //{
            //	String h = new String(buf);
            //	System.out.println(h);
            //}
            
            //PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(),true);
            //writer.print(msg);
            //System.out.println("Sending: " + msg);
            
            //pr.println(msg);
            //wr.writeBytes(msg);
    		//wr.writeBoolean(true);
            //pr.flush();
            //wr.flush();
            //for(Player player : PlayerList.getList())
            //{
            //	sendTextToPlayer(player, msg);
            //}
            Player p = new Player("http://localhost:8000", "obi");
            sendTextToPlayer(p, msg);
             
            System.err.println("Closed Connection");
            in.close();
            
    		//pr.close();
            //writer.close();
            clientSocket.close();
            serverSocket.close();
        }
    }

	public String packageDataForClient() throws UnsupportedEncodingException
	{
		String urlParameters =
		        "fName=" + URLEncoder.encode("???", "UTF-8") +
		        "&lName=" + URLEncoder.encode("???", "UTF-8");
		return urlParameters;
	}
	
	public void sendTextToPlayer(Player player, String msg) throws IOException //IOException manage with disconnection
	{
	    URL url;
	    HttpURLConnection connection = null;  
	    try {
	      //Create connection
	      url = new URL(player.getIP());//targetURL);
	      connection = (HttpURLConnection)url.openConnection();
	      connection.setRequestMethod("POST");
	      connection.setRequestProperty("Content-Type", 
	           "application/x-www-form-urlencoded");
				
	      connection.setRequestProperty("Content-Length", "" + 
	               Integer.toString(msg.getBytes().length));//urlParameters.getBytes().length));
	      connection.setRequestProperty("Content-Language", "en-US");  
				
	      connection.setUseCaches (false);
	      connection.setDoInput(true);
	      connection.setDoOutput(true);

	      //Send request
	      DataOutputStream wr = new DataOutputStream (
	                  connection.getOutputStream ());
	      wr.writeBytes (msg);//urlParameters);
	      wr.flush ();
	      wr.close ();

	      //Get Response	
	      /*
	       * InputStream is = connection.getInputStream();
	      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	      String line;
	      StringBuffer response = new StringBuffer(); 
	      while((line = rd.readLine()) != null) {
	        response.append(line);
	        response.append('\r');
	      }
	      rd.close();
	      return response.toString();
	      */

	    } catch (Exception e) {

	      e.printStackTrace();
	      //return null;

	    } finally {

	      if(connection != null) {
	        connection.disconnect(); 
	      }
	    }
		
		/*String url = player.getIP();
		java.net.URL objUrl = new URL(null, url,new sun.net.www.protocol.https.Handler());
		//URL obj = new URL(url);
		HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
 
		//add reuqest header
		con.setRequestMethod("POST");
 
		String urlParameters = msg;
 
		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		wr.flush();
		wr.close();*/
	}
}
